const app = getApp()
import {
  showMsg
} from '../../../../../../utils/config.js'
import {
  reqConsumerHomeList
} from '../../../../../../request/api.js';
Component({
  properties: {
    show: false,
  },

  options: {
    addGlobalClass: true
  },

  observers: {
    show(val) {
      if (!val) return
      this.getDataList()
    }
  },

  data: {
    navMarginTop: app.globalData.navMarginTop + 'px', //导航栏高度
    dataList: [],
    familyInfo: {},
    scrollIntoFamily: ''
  },

  lifetimes: {
    created() {
      // 初始化数据或绑定方法
      this.getDataList(true)
    },
    attached() {
      this._fooCallback = () => {
        console.log('孙组件收到:');
        this.getDataList(true)
      };
      app.eventBus.on('family', this._fooCallback);
    },
    detached() {
      app.eventBus.off('family', this._fooCallback);
    }
  },

  pageLifetimes: {
    async show() {
      const {
        familyInfo
      } = app.globalData
      const {
        dataList
      } = this.data
      console.log(familyInfo && familyInfo.isUpdate);
      console.log(!(dataList && dataList.length));
      if ((familyInfo && familyInfo.isUpdate) || !(dataList && dataList.length)) {
        console.log('进入');
        this.getDataList(true)
      }
    }
  },

  methods: {
    async getDataList(init = false) {
      let params = {
        userId: app.globalData.userId,
      }
      const res = await reqConsumerHomeList(params)
      if (res.code !== 20000) return showMsg(res.message)
      let {
        rows
      } = res.data
      console.log(rows,'家庭列表');
      this.setData({
        dataList: rows || []
      })

      if (init) {
        // 页面初始时，给全局默认选中第一个家庭
        this.setStorageFamily(rows[0])
        app.globalData.isUpdateCIndex = false
        wx.setStorageSync('isUpdateCIndex', false);

        this.setData({
          familyInfo: rows[0]
        })
        this.onClose('confirm')
      }
    },
    onFamily(e) {
      const {
        item
      } = e.currentTarget.dataset
      console.log(item);
      this.setStorageFamily(item)

      this.setData({
        familyInfo: item,
        scrollIntoFamily: `family${item.id}`,
      })
      this.onClose('confirm')
    },

    setStorageFamily(info) {
      app.globalData.familyInfo = info
      wx.setStorageSync('familyInfo', info);
    },

    goFamily() {
      wx.navigateTo({
        url: '/packageC/pages/family/family/family',
      })
      this.onClose('cancel')
    },

    onClose(action = 'cancel') {
      this.triggerEvent('familyHandle', {
        familyInfo: this.data.familyInfo || {},
        action
      });
    },
  }
})